package com.freedom.monitor.myeye.client.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Collections;
import java.util.Enumeration;
import java.util.LinkedList;
import java.util.List;

public class MachineUtils {
	//
	private static Logger logger = Logger.getLogger(MachineUtils.class);
	private static int GLOBAL_PID = -1;
	private static String GLOBAL_HOST_NAME = "unknown";
	//
	private static String GLOBAL_SERVER_ID = "";

	//
	private MachineUtils() {

	}
	public static String getServerID(){
		return GLOBAL_SERVER_ID;
	}
	// 如果有bug,需要及时提出
	private static String getRealIp() throws Exception {
		String localip = null;// 本地IP，如果没有配置外网IP则返回它
		String netip = null;// 外网IP

		Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();
		InetAddress ip = null;
		boolean finded = false;// 是否找到外网IP
		while (netInterfaces.hasMoreElements() && !finded) {
			NetworkInterface ni = netInterfaces.nextElement();
			Enumeration<InetAddress> address = ni.getInetAddresses();
			while (address.hasMoreElements()) {
				ip = address.nextElement();
				if (!ip.isSiteLocalAddress() && !ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == -1) {// 外网IP
					netip = ip.getHostAddress();
					finded = true;
					break;
				} else if (ip.isSiteLocalAddress() && !ip.isLoopbackAddress()
						&& ip.getHostAddress().indexOf(":") == -1) {// 内网IP
					localip = ip.getHostAddress();
				}
			}
		}

		if (netip != null && !"".equals(netip)) {
			return netip;
		} else {
			return localip;
		}
	}

	private static List<Integer> getPortByCmd(String[] cmd) {
		// 先获取tcp端口
		Runtime run = Runtime.getRuntime();
		BufferedReader br = null;
		Process p = null;
		List<Integer> ports = new LinkedList<Integer>();
		try {
			p = run.exec(cmd);
			br = new BufferedReader(new InputStreamReader(p.getInputStream()));
			String str = null;
			while ((str = br.readLine()) != null) {
				str = str.trim();
				String str0 = str;
				String str1 = str;
				try {
					str0 = str0.split(":::")[1].trim();
					ports.add(Integer.parseInt(str0));
				} catch (Exception e) {
					str1 = str1.split(":")[1].split(" ")[0].trim();
					ports.add(Integer.parseInt(str1));
				}
			}
			Collections.sort(ports);
			p.waitFor();
		} catch (Exception e) {
		} finally {
			if (br != null)
				try {
					br.close();
				} catch (IOException e) {
				}
			if (p != null)
				p.destroy();
		}
		return ports;
	}

	static {
		// 在类的初始化块中，只会执行1次,后面一直使用本次获取的结果
		try {
			final RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
			final String info = runtime.getName();
			//logger.info("ManagementFactory.getRuntimeMXBean().getName--->" + info);
			String[] strArray = info.split("@");
			GLOBAL_PID = Integer.parseInt(strArray[0]);
			GLOBAL_HOST_NAME = strArray[1].trim();
		} catch (Exception e) {
			GLOBAL_PID = -1;
			GLOBAL_HOST_NAME = "unknown";
			logger.error("fail to find @ from runtime info...");
		}
		// 获取ip,如果没取到，就设置为域名
		String ip = null;
		try {
			ip = getRealIp();
		} catch (Exception e) {
			ip = "";
		}
		if (ip == null || "".equals(ip.trim())) {// 修正一下
			ip = GLOBAL_HOST_NAME;
		}
		System.out.println("ip ---> " + ip);
		//
		//
		//
		// 获取tcp端口
		List<Integer> ports = getPortByCmd(
				new String[] { "/bin/bash", "-c", "netstat -tnlp|grep " + GLOBAL_PID });
		// 如果tcp端口为空则获取udp
		if (ports == null || ports.size() <= 0) {
			ports = getPortByCmd(new String[] { "/bin/bash", "-c", "netstat -unlp | grep " + GLOBAL_PID });
		}
		// 整理&拼接
		String port = ports.toString().replaceAll("\\s*", "");
		GLOBAL_SERVER_ID = ip + "-" + port;
	}

	public static void main(String[] args) {
		long begin = System.currentTimeMillis();
		long end = System.currentTimeMillis();
		System.out.println("cost " + (end - begin) + " ms");
		//
		begin = System.currentTimeMillis();
		end = System.currentTimeMillis();
		System.out.println("cost " + (end - begin) + " ms");
		//
		begin = System.currentTimeMillis();
		end = System.currentTimeMillis();
		System.out.println("cost " + (end - begin) + " ms");
		System.out.println("" + GLOBAL_SERVER_ID);
		String str = "tcp        0      0 0.0.0.0:9012            0.0.0.0:*               LISTEN      3082/java8";
		str = str.trim();
		String[] test = str.split(":");
		System.out.println(test[1]);
		test = test[1].split(" ");
		System.out.println(test[0]);
		// System.out.println(Integer.parseInt(str));
	}

}
